package com.example.gallery;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.example.board.R;
import com.example.board.R.layout;



public class InsertActivity extends Activity implements OnClickListener {
	private static final int TAKE_CAMERA = 1; // ī�޶� ���� �ڵ尪 ����
	private static final int TAKE_GALLERY = 2; // �ٹ��ÿ� ���� ���� �ڵ尪 ����
	static final String TAG = "INSERT ACTIVITY";
	private static final int REQUEST_CODE_IMAGE = 3;
	DisplayMetrics metrix = new DisplayMetrics();

	Context mContext;
	
	Common common = new Common();
	BitmapToFile toFile;
	static File path = null;
	SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
	long time ;
	String file_name;
	String url ;
	int width;
	int height;
	int portion = 360;
	String image_path;
	boolean check = false;
	//	Uri mImageCaptureUri; //�����̸� ����
	
	TextView tv_board_no;
	TextView et_id;
	EditText et_title;
	EditText et_content;
	Button btn_save;
	ImageButton btn_camera;
	ImageButton btn_gallery;
	LinearLayout image_layout;
	ImageView iImageView;
	Builder listDialog;
	ImageView mImageView;
	Bitmap mBitmap;
	Bitmap temp;
	FileOutputStream fos = null ;
	OutputStream out = null;
	GridView grid_image;
	
	String ID;
	String TITLE;
	String CONTENT;
	String DATE;
	int Board_NO;
	ArrayList<ImageDTO> last_image_list;
	String last_image;

	
	/*
	 * ArrayList<?> bitmapList;
	final int AVAILABE_WIDTH = (int)(360 * getResources().getDisplayMetrics().density);
	float scale = getResources().getDisplayMetrics().density;
	final int startMargine  = (int) (10  * scale);
    final int tvheightPx = (int) (28 * scale);
    final int vwidthPx  = (int) (3  * scale);
    final int vsize = (int) (3 * scale);
    final int padding = (int) (7 * scale);*/
    

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.insert);
//		LinearLayout layout = (LinearLayout) findViewById(R.id.ll_imageView);
		
		
		Intent intent = getIntent();
		Bundle b = getIntent().getExtras();
		Board_NO = b.getInt("BOARD_NO");
	
		/*	
		ListActivity activity = new ListActivity();
		activity.getImagePath();
		*/
		
		//ȭ�� �ػ� 
		getWindowManager().getDefaultDisplay().getMetrics(metrix);
		width = metrix.widthPixels;
		height = metrix.heightPixels;
		
		iImageView = (ImageView) findViewById(R.id.iImageView);
		et_id = (TextView) findViewById(R.id.et_id);
		tv_board_no = (TextView) findViewById(R.id.tv_board_no);
		et_title = (EditText) findViewById(R.id.et_title);
		et_content = (EditText) findViewById(R.id.et_content);
		btn_save = (Button) findViewById(R.id.btn_save);
		btn_camera = (ImageButton) findViewById(R.id.btn_camera);
		btn_gallery = (ImageButton) findViewById(R.id.btn_gallery);
//		grid_image = (GridView) findViewById(R.id.grid_image);
		
//		mImageView = (ImageView) findViewById(R.id.mImageView);
		
		path = common.getDir();	//file_path :/storage/emualted/0/Pictures/Gallery_Board

		btn_save.setOnClickListener(this);
		btn_camera.setOnClickListener(this);
		btn_gallery.setOnClickListener(this);
		
		SharedPreferences prf = getSharedPreferences("login", 0);
		ID = prf.getString("id", "");

		if (ID == null || ("").equals(ID)) {
			Toast.makeText(getApplicationContext(), "�α��� �� �ٽ� �̿��� �ּ���",
					Toast.LENGTH_LONG).show();
			common.go(this, MainActivity.class);
		}
		Log.i(TAG, "���� ������ : "+path);
		et_id.setText(ID);
		tv_board_no.setText(Board_NO+"");
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
	}

	@Override
	public void onClick(View v) {
		BoardHandler db = BoardHandler.open(this);
		ImageHandler imageDB = ImageHandler.open(this);
		
		BoardDTO board;
		int succ = 0;
		switch (v.getId()) {
		case R.id.btn_save:

			TITLE = et_title.getText().toString();
			CONTENT = et_content.getText().toString();
			
			board = new BoardDTO(TITLE, CONTENT, ID);
			if(checkValidity()){			//check validity
				long cnt = db.insert(board);

				if (cnt < 0) {
					Toast.makeText(getApplicationContext(), "failed save content...",
							Toast.LENGTH_SHORT).show();
					return;
				} else {
//					common.go(this, BoardListActivity.class);
					Intent intent = new Intent(this, BoardListActivity.class);
					startActivity(intent);
					finish();
				}
				
			}
//			Log.i(TAG, "save image parameter"+ID+Board_NO+image_path);
			
//			if(image_path != null ){
//				ImageDTO dto = new ImageDTO(ID, Board_NO, image_path);
//				succ = (int) imageDB.insert(dto);
//			}
			
			break;
		case R.id.btn_camera :
//			lDial();	//Dialog List로 선택 시 사용
			Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			time = System.currentTimeMillis();
			file_name = format.format(time);
			url = file_name+".jpg";
			
			
			File file = new File(path, url);
			intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
			
			intent2.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, url);
			startActivityForResult(intent2, TAKE_CAMERA);
			
			Log.i(TAG, "External Storage Directory : "+path+"\nfile : "+file);

			break;
			
		case R.id.btn_gallery :
		
			Intent intent = new Intent(Intent.ACTION_PICK);
			intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
			intent.setData(Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(intent, TAKE_GALLERY);
		
		
		/*
			Intent intent = new Intent(this, AlbumList.class);
			startActivityForResult(intent, TAKE_GALLERY);
		*/
		
			
			/*Intent intent = new Intent(this, ListActivity.class);
			startActivityForResult(intent, TAKE_GALLERY);
			*/
			
		default:
			break;
		}
	}

	/*
	
	사진촬영, 앨범선택 하는 DialogList
	 */
	public void lDial() {
		final String[] items = { "�ٹ�", "�Կ�" };

		listDialog = new AlertDialog.Builder(this);
		listDialog.setTitle("����")
				.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Log.i(TAG, "which : " + which);
						Log.i(TAG, "items : " + items);
						Log.i(TAG, "items[which] : " + items[which]);
						
						switch (which) {
						case 0:	// 앨범선택
							Intent intent = new Intent(Intent.ACTION_PICK);
							intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
							startActivityForResult(intent, TAKE_GALLERY);
							break;

						case 1:	// 촬영
							Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							/*File dir = common.getDir();
							mImageCaptureUri = Uri.fromFile(new File(dir, url));*/
							time = System.currentTimeMillis();
							file_name = format.format(time);
							url = file_name+".jpg";
							/*
							 * 
							 */
							intent2.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, url);
							Log.i(TAG, "onclick ī�޶� �Կ� url : "+path +"/"+url);
							startActivityForResult(intent2, TAKE_CAMERA);
						/*	
							File file = new File(path, url);
							Uri outputFileUri;
							outputFileUri = Uri.fromFile(file);
							Log.i(TAG, "ȭ���������"+file_name);
							intent2.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
							startActivityForResult(intent2, TAKE_CAMERA);
						*/	
							break;

						default:
							break;
						}
					}
				}).setNegativeButton("�ݱ�", null).show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.i(TAG, "onActivityResult");
	
		LinearLayout layout = (LinearLayout) findViewById(R.id.ll_imageView);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.gravity = Gravity.CENTER_HORIZONTAL;
		
		ImageHandler imageDB = ImageHandler.open(this);

		
		
		if(resultCode != RESULT_OK){
			return;
		}
		
		switch (requestCode) {
		case TAKE_CAMERA:	//
			
			Bundle extras = data.getExtras();
			if(extras != null){
				mBitmap = (Bitmap)extras.get("data");	//data�� ��??? ��??? thumbnail??
				
				
			/*	
				ImageView iv = new ImageView(this);
				iv.setAdjustViewBounds(true);
				iv.setId(R.id.iImageView);
				iv.setImageBitmap(mBitmap);
				iv.setLayoutParams(params);
				layout.addView(iv);
			*/
				
				last_image_list = new ArrayList<ImageDTO>();
				last_image_list = common.getLastImage(this);
				last_image = last_image_list.get(0).NAME;
				Log.i(TAG, "captured_image : "+last_image_list.get(0).NAME);
				
			/*	BitmapFactory.Options option = new BitmapFactory.Options();
				option.inSampleSize = 4;*/
				
				Bitmap bitmap = BitmapFactory.decodeFile(last_image);
				iImageView.setImageBitmap(bitmap);
				
//				iImageView.setImageURI(Uri.parse(last_image));
				
//				iImageView.setImageBitmap(mBitmap);
				
//				createImageView(mBitmap);
				
				
				/*	
				try {
					time = System.currentTimeMillis();
					file_name = format.format(time);
					String full_path = path+"/"+file_name+".jpg";	//���ϰ�� �� ���ϸ�
				
					File image_file = new File(full_path);	//���ϻ�
					fos = new FileOutputStream(image_file);
//					Bitmap resize = Bitmap.createScaledBitmap(mBitmap, width, height, true);	//resize bitmap
					
					mBitmap.compress(CompressFormat.JPEG, 100, fos);	//
					Log.i(TAG, "full path : "+ full_path);*/
//					MediaScanner mscanner = new MediaScanner(getApplicationContext(), image_file);
					
					long succ = 0;
					
					ImageDTO dto = new ImageDTO(ID, Board_NO, last_image);
					succ = imageDB.insert(dto);
					
					if(succ > 0){
						Log.i(TAG, "image save success");
					}
					else{
						Log.i(TAG, "image save failed");
					}
			/*	} 
				
				catch (Exception e) {
					Log.e(TAG,"Bitmap to File Error : "+ e.toString());
				}
				finally{
					try{
						fos.close();
					}
					catch(Exception e){
						Log.e(TAG, "fos close ERROR : "+e.toString());
					}
				}
				*/
			}
			
//			Bitmap bitmap = BitmapFactory.decodeFile("imagepath");	//�̹��� ��������
			/*mImageView.setImageBitmap(mBitmap);	//�̹����信 �Ѹ���
			mImageView.setScaleType(ImageView.ScaleType.FIT_XY);	//scale ���߱�	
			*/
			break;
		case TAKE_GALLERY:
			
		/*	
		 	Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			this.startActivityForResult(intent, REQUEST_CODE_IMAGE);
			Log.i(TAG, "take_gallery");
			finish();
		*/
			
			Uri uri = data.getData();
			String path = uri.getPath();
			Log.i(TAG, "image uri of pick from gallery  : "+path);
			
			image_path = common.getRealImagePath(this, uri);	//Uri to real file path of image
			
			int succ = 0;
			if(image_path != null ){
				ImageDTO dto = new ImageDTO(ID, Board_NO, image_path);
				succ = (int) imageDB.insert(dto);
			}
			
			Log.i(TAG, "save image parameter..."+ID+Board_NO+image_path);

			Bitmap bitmap = BitmapFactory.decodeFile(image_path);
			iImageView.setImageBitmap(bitmap);
			
		/*	
			int succ = 0;
			ImageDTO dto = new ImageDTO(ID, Board_NO, image_path);
			succ = (int) imageDB.insert(dto);
		*/
			
	/*		ImageView iv = new ImageView(this);
			iv.setAdjustViewBounds(true);
			iv.setId(R.id.iImageView);
			iv.setImageURI(uri);
			iv.setLayoutParams(params);
			layout.addView(iv);*/
			
//			iImageView.setImageURI(Uri.parse(image_path));	//앨범을 여러개 가져올 경우 표시가 안 됨
			
			createImageView(uri);
			/*MediaScanner ms = new MediaScanner();
			ms.getAlbum();*/
		
			
			break;

		
		case REQUEST_CODE_IMAGE : 
			/*Uri uri = data.getData();
			String path = uri.getPath();
			Log.i(TAG, "이미지 경로 : "+path);*/
			
		default:
			break;
		}
		
	}

	public void createImageView(Bitmap bitmap){
		LinearLayout layout = (LinearLayout) findViewById(R.id.ll_imageView);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.gravity = Gravity.CENTER_HORIZONTAL;
		
		ImageView iv = new ImageView(this);
		iv.setAdjustViewBounds(true);
		iv.setId(R.id.iImageView);
		iv.setImageBitmap(mBitmap);
		iv.setLayoutParams(params);
		layout.addView(iv);
		
	}
	
	
	public void createImageView(Uri uri){
		LinearLayout layout = (LinearLayout) findViewById(R.id.ll_imageView);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.gravity = Gravity.CENTER_HORIZONTAL;
		
		ImageView iv = new ImageView(this);
		iv.setAdjustViewBounds(true);
		iv.setId(R.id.iImageView);
		iv.setImageURI(uri);
		iv.setLayoutParams(params);
		layout.addView(iv);
		
	}
	
	public boolean checkValidity(){
		TITLE = et_title.getText().toString();
		CONTENT = et_content.getText().toString();
			if(("").equals(TITLE)){
				check = false;
				Toast.makeText(getApplicationContext(), "제목을 입력해 주세요",	 Toast.LENGTH_LONG).show();
			}
			else if(("").equals(CONTENT)){
				check = false;
				Toast.makeText(getApplicationContext(), "내용을 입력해 주세요",	 Toast.LENGTH_LONG).show();
			}
			else{
				check = true;
			}
		return check;
	}
	/*private void handleSmallCameraPhoto( Intent intent){
		Bundle extras = intent.getExtras();
		mImageBitmap = (Bitmap)extras.get("data");
		mImageView.setImageBitmap(mImageBitmap);
	}*/

}
